/*
Package model
@Time : 2022/12/20 21:31
@Author : 董胜烨
@File : db
@Software: GoLand
@note:
*/
package model

import (
	"database/sql"
	setting "employee/pkg"
	"employee/pkg/utils"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

var (
	db  *sql.DB
	err error
)

func Setup() {
	dbLinkStr := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
		setting.DataBaseSetting.User,
		setting.DataBaseSetting.Password,
		setting.DataBaseSetting.Host,
		setting.DataBaseSetting.Name)
	db, err = sql.Open(setting.DataBaseSetting.Type, dbLinkStr)
	if err != nil {
		log.Fatalln("Open Database Error", err)
	}
	err = db.Ping()
	if err != nil {
		log.Fatalln("Link Database Error", err)
	}

}

func Insert(sql string, params ...interface{}) int64 {
	// 注意：这里必须是params... 不然会转成数组类型了
	res, err := db.Exec(sql, params...)
	// 打印上一次插入自增的id
	if res != nil {
		insertId, _ := res.LastInsertId()
		return insertId
	} else {
		fmt.Printf("插入失败：%v\n", err)
		return 0
	}

}

func Delete(sql string, params ...interface{}) bool {
	res, err := db.Exec(sql, params...)
	if err != nil {
		fmt.Printf("删除失败：%v\n", err)
		return false
	} else {
		fmt.Println(res.RowsAffected())
		return true
	}
}

func Update(sql string, params ...interface{}) bool {
	res, err := db.Exec(sql, params...)
	if err != nil {
		fmt.Printf("更新失败：%v\n", err)
		return false
	} else {
		fmt.Println(res.RowsAffected())
		return true
	}
}
func QueryAll(SQL string) []map[string]string { //通用查询寒素
	rows, err := db.Query(SQL)
	defer rows.Close()
	if err != nil {
		fmt.Printf("查询出错:\nSQL:\n%s, 错误详情:%s\n", db, err.Error())
		return nil
	}
	//获取列名cols
	cols, _ := rows.Columns()
	if len(cols) > 0 {
		var ret []map[string]string
		for rows.Next() {
			buff := make([]interface{}, len(cols))
			data := make([][]byte, len(cols)) //数据库中的NULL值可以扫描到字节中
			for i, _ := range buff {
				buff[i] = &data[i]
			}
			rows.Scan(buff...) //扫描到buff接口中，实际是字符串类型data中
			//将每一行数据存放到数组中
			dataKv := make(map[string]string, len(cols))
			for k, col := range data { //k是index，col是对应的值

				if cols[k] == "hire_date" || cols[k] == "birth_date" || cols[k] == "date" {
					col = []byte(utils.RfcToCom(string(col)))
				}
				dataKv[cols[k]] = string(col)
			}
			ret = append(ret, dataKv)
		}

		return ret
	} else {
		return nil
	}
}
